package com.geekgo.geekjob.util;

import com.alibaba.fastjson.JSON;
import com.geekgo.geekjob.Constants;
import com.geekgo.geekjob.enums.ScheduleEnum;
import com.geekgo.geekjob.exception.GGException;
import com.geekgo.geekjob.model.ScheduleJobModel;
import org.quartz.*;

import java.util.Objects;

/**
 * 定时器工具
 *
 * @author HeHaoyang
 * @create 2017-06-27 18:23
 **/
public final class ScheduleUtils {

    private static final String JOB_NAME_PREFIX = Constants.JOB_NAME_PREFIX;

    /**
     * 获取触发器key
     * @param jobId
     * @return
     */
    public static TriggerKey getTriggerKey(Long jobId){
        return TriggerKey.triggerKey(JOB_NAME_PREFIX + jobId);
    }

    /**
     * 获取job key
     * @param jobId
     * @return
     */
    public static JobKey getJobKey(Long jobId){
        return JobKey.jobKey(JOB_NAME_PREFIX + jobId);
    }

    /**
     * 获取表达式触发器
     * @param scheduler
     * @param jobId
     * @return
     */
    public static CronTrigger getCronTrigger(Scheduler scheduler, Long jobId){
        try {
            return (CronTrigger)scheduler.getTrigger(getTriggerKey(jobId));
        } catch (SchedulerException e) {
            throw new GGException("获取定时任务CronTrigger出现异常",e);
        }
    }

    /**
     * 创建任务
     * @param scheduler
     * @param scheduleJob
     * @param clazz  QuartzJobBean 实现类
     */
    public static void createScheduleJob(Scheduler scheduler, ScheduleJobModel scheduleJob,Class<? extends Job> clazz){

        try {
            //构建job信息
            JobDetail jobDetail = JobBuilder.newJob(clazz).withIdentity(getJobKey(scheduleJob.getId())).build();

            //表达式调度构建器
            CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(scheduleJob.getCronExpression()).
                    withMisfireHandlingInstructionDoNothing();

            //按新的cronExpression表达式构建一个新的trigger
            CronTrigger cronTrigger = TriggerBuilder.newTrigger().withIdentity(getTriggerKey(scheduleJob.getId())).withSchedule(scheduleBuilder).build();

            //放入参数，运行时的方法可以获取
            jobDetail.getJobDataMap().put(ScheduleJobModel.JOB_PARAM_KEY, JSON.toJSONString(scheduleJob));

            scheduler.scheduleJob(jobDetail,cronTrigger);

            //暂停任务
            if(Objects.equals(scheduleJob.getEnable(), ScheduleEnum.PAUSE.getValue())){
                pauseJob(scheduler,scheduleJob.getId());
            }
        } catch (SchedulerException e) {
            throw new GGException("创建定时任务失败！",e);
        }
    }

    /**
     * 更新定时任务
     * @param scheduler
     * @param scheduleJob
     */
    public static void updateScheduleJob(Scheduler scheduler, ScheduleJobModel scheduleJob){

        try {
            TriggerKey triggerKey = getTriggerKey(scheduleJob.getId());

            //表达式调度构建器
            CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(scheduleJob.getCronExpression())
                    .withMisfireHandlingInstructionDoNothing();

            CronTrigger trigger = getCronTrigger(scheduler, scheduleJob.getId());

            //按新的cronExpression表达式重新构建trigger
            trigger = trigger.getTriggerBuilder().withIdentity(triggerKey).withSchedule(scheduleBuilder).build();

            //参数
            trigger.getJobDataMap().put(ScheduleJobModel.JOB_PARAM_KEY, JSON.toJSONString(scheduleJob));

            scheduler.rescheduleJob(triggerKey, trigger);

            //暂停任务
            if(Objects.equals(scheduleJob.getEnable(), ScheduleEnum.PAUSE.getValue())){
                pauseJob(scheduler, scheduleJob.getId());
            }
        } catch (SchedulerException e) {
            throw new GGException("更新定时任务失败！",e);
        }
    }

    /**
     * 立即执行任务
     * @param scheduler
     * @param scheduleJob
     */
    public static void run(Scheduler scheduler, ScheduleJobModel scheduleJob){

        try {
            //参数
            JobDataMap jobDataMap = new JobDataMap();
            jobDataMap.put(ScheduleJobModel.JOB_PARAM_KEY,JSON.toJSONString(scheduleJob));
            scheduler.triggerJob(getJobKey(scheduleJob.getId()),jobDataMap);
        } catch (SchedulerException e) {
            throw new GGException("立即执行任务失败!",e);
        }
    }

    /**
     * 暂停任务
     * @param scheduler
     * @param jobId
     */
    public static void pauseJob(Scheduler scheduler, Long jobId){

        try {
            scheduler.pauseJob(getJobKey(jobId));
        } catch (SchedulerException e) {
            throw new GGException("暂停定时任务失败！",e);
        }
    }

    /**
     * 恢复任务
     * @param scheduler
     * @param jobId
     */
    public static void resumeJob(Scheduler scheduler, Long jobId){
        try {
            scheduler.resumeJob(getJobKey(jobId));
        } catch (SchedulerException e) {
            throw new GGException("恢复定时任务失败！",e);
        }
    }

    /**
     * 删除任务
     * @param scheduler
     * @param jobId
     */
    public static void deleteJob(Scheduler scheduler, Long jobId){
        try {
            scheduler.deleteJob(getJobKey(jobId));
        } catch (SchedulerException e) {
            throw new GGException("删除定时任务失败！",e);
        }
    }

}
